<template>
  <div class="page-containter">
    <uni-nav-bar fixed shadow :border="false" :title="(detail && detail.time) ? detail.time : (detail && detail.name) || ''" left-icon="left" @clickLeft="onClickLeft" >
      <template #right>
        <button class="nav-bar-btn" type="primary" size="medium" round :loading="saveLoading" :disabled="btnStatus" @click="submit">提交</button>
      </template>
      <template #bottom>
        <div class="progress-wrap flex-wrap flex-middle" id="percentage">
          <van-progress class="flex-item" :percentage="percentage" :show-pivot="false" color="var(--color)"></van-progress>
        </div>
      </template>

    </uni-nav-bar>
    <div class="page-content isWap" v-if="detail">
      <div class="page-bg">
        <div class="page-title fs-24 common-wrap">{{detail.name}}</div>
        <div class="page-subtitle fs-14 common-wrap">{{detail.brief}}</div>
      </div>
      <div class="common-wrap content-wrap">
        <div class="test-item" v-for="(item,index) in listData" :key="index">
          <exam
              :testItem="item"
              :testIndex="item.index"
              :showIndex="getShowIndex(listData, item)"
              :optionsList="answer[item.questionsId].options"
              :val="answer[item.questionsId].val"
              :extendAnswer="answer[item.questionsId].extendAnswer"
              :customAnswer="answer[item.questionsId].customAnswer"
              :edit="false"
              :isMustAnswer="detail.isAllAnswer === '1'"
              @input="changeInput"
              @openLink="openLink"></exam>
        </div>
        <div class="btn-wrap flex-wrap flex-middle flex-center">
          <button
              round
              class="btn"
              type="primary"
              @click="setPage(pageAll.current - 1, true)"
              v-if="pageAll && pageAll.current > 1">上一页</button>
          <button
              round
              class="btn"
              type="primary"
              @click="setPage(pageAll.current + 1, true)"
              v-if="pageAll && pageAll.current < pageAll.total">下一页</button>
        </div>
      </div>
    </div>
    <van-action-sheet v-model="actionShow" title="查看跳转">
      <iframe :src="actionURL" id="iframepage" name="iframepage" frameBorder=0 width="100%" style="height: 80vh;"></iframe>
    </van-action-sheet>
  </div>
</template>
<script>
import {
  mapGetters
} from 'vuex'
import { sha256 } from 'js-sha256'
import exam from '@/view/questionnaire/exam.vue'
import { parse, stringify, copyBasic, deepClone, getFormTime, getCurrentTime } from '@/assets/js/util.js'
import VanProgress from "@/components/vant/van-progress/van-progress.vue";
import VanActionSheet from "@/components/vant/van-action-sheet/van-action-sheet.vue";
import VanForm from "@/components/vant/van-form/van-form.vue";
import VanField from "@/components/vant/van-field/van-field.vue";
import VanDialog from "@/components/vant/van-dialog/van-dialog.vue";
import mockData from "@/mock/survey/question.json"
export default {
  components: {VanProgress, VanActionSheet, VanForm, VanField, VanDialog, exam},
  head() {
    return {
      title: this.detail && this.detail.name
    }
  },
  data() {
    return {
      navBarShow: false,
      detail:{
		  name:""
	  },
      source: '',
      id: '',
      saveLoading: false,
      btnStatus: false,
      currentTime: 0,
      time: 0,
      listAll: [],
      pageAll: null,
      answer: {},

      showDialog: false,
      actionShow: false,
      actionURL: '',
      progressTop: 0,
      percentage: 0,
      percentageStatus: false,
      // 签名
      signatureDialog: false,
      signatureLoading: false,
      signatureBase64: '',
    }
  },
  onLoad(query) {
    this.id = query.id || ''
    this.source = query.source || ''
    this.navBarShow = true

  },
  onUnload() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  mounted() {
    this.getStatus()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  "detail.time"(val) {
    uni.setNavigationBarTitle({
      title: val
    })
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  onPageScroll(e) {
    this.progressTop = e.scrollTop + 'px'
    if (this.percentageTime) {
      clearTimeout(this.percentageTime)
    }
    this.percentageStatus = false
    this.percentageTime = setTimeout(() => {
      this.percentageStatus = true
    }, 200)
  },
  computed: {
    listData() {
      if (!this.pageAll) {
        return this.listAll
      }
      return this.getPageData(this.listAll, this.pageAll)
    }
  },
  methods: {
    onClickLeft() {
      uni.navigateBack({ delta: 1 })
    },

    setPercentage() {
      let arr = 0
      let len = 0
      for(let i in this.answer) {
        if (this.answer[i].type !== 'remark' && this.answer[i].type !== 'partition')
          arr++
        if (this.answer[i].flag) {
          len++
        }
      }
      this.percentageStatus = false
      this.percentage = Math.ceil(len/arr*100)
      setTimeout(() => {
        this.percentageStatus = true
      }, 100)
    },

    getShowIndex(list, item) {
      let arr = list.filter(e => e.questionsType !== 'remark' && e.questionsType !== 'partition')
      return arr.findIndex(e => e === item)
    },

    getStatus() {
		 this.getInfo();
    },
    getInfo(code, done) {
      let params = {
        surveyDevice: 1,
        surveyId: this.id
      }
      if (code) {
        params.checkPassword = code
      }
	  let res=mockData.data;
        if (res.latestSubmitDate) {
          res.surplus = Math.floor((getCurrentTime(res.latestSubmitDate) - getCurrentTime(res.nowDate))/1000)
          res.time = getFormTime(res.surplus)
        }
        if (res.participateDate) {
          res.timeout = Math.floor((getCurrentTime(res.nowDate) - getCurrentTime(res.participateDate))/1000)
        }
        if (code) {
          this.showDialog = false
        }
        let data
        this.detail = res
        this.time = res.autoSaveTime * 60
        data = this.setIndex(res.dataJSON)
        this.listAll = data.list
        this.pageAll = data.page
        this.answer = data.answer
        uni.setNavigationBarTitle({
          title: this.detail.name
        })
        done && done(false)
		this.setTimer()
    },
    // 获取当前分页数据
    getPageData(list, page, type) {
      let start = (page.current - 1) * page.size
      let end = page.current * page.size - 1
      return list.filter((question, i) => i >= start && i <= end)
    },
    // 处理移动
    handleMove(id) {
      let index, page
      if (!this.pageAll || !this.detail.showQuestionsNumPerPage) {
        this.startMove(id)
        return
      }
      index = parseInt((id).replace('child', '')) + 1
      page = Math.ceil(index/this.detail.showQuestionsNumPerPage)
      if (this.pageAll.current !== page) {
        this.setPage(page)
        this.$nextTick(() => {
          this.startMove(id)
        })
      } else {
        this.startMove(id)
      }
    },
    // 开始移动
    startMove(id){
      /* document.querySelector(`#${id}`).scrollIntoView({
          behavior: "smooth", // 平滑过渡
          block: "center"
      }) */
    },
    setPage (page, status) {
      if (page > 0 && page <= this.pageAll.total) {
        this.$set(this.pageAll, 'current', page)
      }
      if (status) {
        this.$nextTick(() => {
          this.startMove('percentage')
        })
      }
    },
    // 整理问题、问题右侧列表、答案列表
    setIndex(list) {
      let arr = []
      let answer = {}
      let page = null
      let pageSize = this.detail.showQuestionsNumPerPage
      if (list.length) {
        arr = list.map((item, ind) => {
          item.index = ind
          answer[item.questionsId] = {
            type: item.questionsType,
            must: item.isMustAnswer,
            flag: item.questionsRecords && item.questionsRecords.answerFlag === '1',
            index: ind,
            location: 'child' + ind,
            extendAnswer: item.questionsRecords && item.questionsRecords.extendAnswerContentJson ? this.setExtend(parse(item.questionsRecords.extendAnswerContentJson), item.questionsRecords.answerOptionsId) : '',
            customAnswer: item.questionsRecords && item.questionsRecords.customAnswerContentJson ? this.setCustom(parse(item.questionsRecords.customAnswerContentJson), item.questionsRecords.answerOptionsId) : '',
            val: this.setVal(item.questionsType, (item.questionsRecords && item.questionsRecords.answerOptionsId) || (item.questionsRecords && item.questionsRecords.answerContent) || '')
          }
          if ((item.questionsType === 'radio' || item.questionsType === 'check') && item.optionsContent && item.optionsContent.length) {
            let arr = []
            item.optionsContent.forEach(it => {
              arr[it.optionsId] = it
            })
            answer[item.questionsId].options = arr
          } else if (item.questionsType === 'input' && item.content) {
            let reg = /\[\[\*\]\]/ig
            let arr = item.content.match(reg)
            item.optionsContent = arr ? arr.length : 0
          }
          if (item.remark) {
            item.remark = parse(item.remark)
          }
          if (item.questionsType === 'input' || item.questionsType === 'inputs') {
            answer[item.questionsId].optionsLength = typeof item.optionsContent === 'number' ? item.optionsContent : item.optionsContent && item.optionsContent.length || 0
          }
          return item
        })
        if (pageSize) {
          page = {
            size: pageSize,
            current: 1,
            total: Math.ceil(list.length/pageSize)
          }
        }
      }
      return {
        list: arr,
        page: page,
        answer: answer
      }
    },
    setExtend(list, id) {
      let current = list.find(e => e[id])
      return current ? current[id] : ''
    },
    setCustom(list, ids) {
      let current,
          currentKey
      ids = ids.split(',')
      ids.forEach(item => {
        let key = item
        if (list.find(e => e[item])) {
          current = list.find(e => e[item])
          currentKey = key
        }
      })
      return current ? current[currentKey] : ''
    },
    setVal(type, val){
      if (type === 'check' || type === 'vote') {
        return val ? val.split(',') : []
      } else if (type === 'inputs') {
        return val ? parse(val) : []
      } else if (type === 'input') {
        val = val ? parse(val) : []
        if (typeof val === 'string'){
          val = [val]
        }
        return val
      }
      return val
    },
    changeInput(type, key, val, k) {
      if (k) {
        this.answer[key][k] = val
        return false
      } else if (type === 'radio') {
        this.answer[key].extendAnswer = ''
      } else if (type === 'check' && !this.answer[key].val.find(e => this.answer[key].options[e].openCustomAnswer === '1')) {
        this.answer[key].customAnswer = ''
      }
      if (type === 'vote') {
        this.setChooseCount(key, val)
      }
      if ((type === 'check' || type === 'select' || type === 'vote') && val.length) {
        this.answer[key].flag = true
      } else if (type === 'check' || type === 'select' || type === 'vote') {
        this.answer[key].flag = false
      } else if ((type === 'inputs' || type === 'input') && val.length && val.filter(e => e).length && val.filter(e => e).length === this.answer[key].optionsLength) {
        this.answer[key].flag = true
      } else if (type === 'input' && !this.answer[key].optionsLength) {
        this.answer[key].flag = true
      } else if (type !== 'check' && type !== 'inputs' && type !== 'input' && val) {
        this.answer[key].flag = true
      } else {
        this.answer[key].flag = false
      }
      if (this.answer[key].flag && this.listAll[this.answer[key].index].fillVali) {
        this.$set(this.listAll[this.answer[key].index], 'fillVali', false)
      }
      this.answer[key].val = val
      this.setPercentage()
    },
    setChooseCount(key, val) {
      this.listAll = this.listAll.map(e => {
        if (e.questionsId === key) {
          e.optionsContent = e.optionsContent.map(item => {
            let i = val.indexOf(item.optionsId) >= 0 ? 1 : 0
            if (!item.hasOwnProperty('defaultCount')) {
              item.defaultCount = item.chooseCount || 0
            }
            item.chooseCount = item.defaultCount + i
            return item
          })
        }
        return e
      })
    },
    // 开始计时
    setTimer(){
      this.timer = setInterval(this.handleTime, 1000)
    },
    // 处理时间
    handleTime() {
      this.currentTime++
      // 倒计时
      if (this.detail.surplus >= 0) {
        this.detail.time = getFormTime(this.detail.surplus - this.currentTime)
      }
      // 超时强制提交
      if (this.detail.surplus > 0 && this.detail.surplus <= this.currentTime || this.detail.surplus <= 0) {
        this.submitAuto()
      }
      //  定时保存
      if (this.time && this.currentTime%this.time === 0) {
        this.save()
      }
      //  按键状态
      if (typeof this.detail.timeout === 'number' && this.detail.timeout + this.currentTime >= this.detail.shortestTimeLimit) {
        this.btnStatus = false
      } else if (typeof this.detail.timeout === 'number') {
        this.btnStatus = true
      }
      if (!this.detail.surplus && !this.time && (this.detail.timeout && !this.btnStatus && this.timer || !this.detail.timeout)) {
        clearInterval(this.timer)
      }
    },
    // 获取提交答案
    getJson(current){
      let filled = [],
          extendFilled = [],
          customFilled = [],
          unfilled = []
      for (let id in current) {
        if (current[id].flag && (current[id].type === 'radio')){
          filled.push({
            questionsId: id,
            answerOptionsId: current[id].val,
            answerContent: ''
          })
        } else if (current[id].flag && (current[id].type === 'check' || current[id].type === 'select' || current[id].type === 'vote')) {
          filled.push({
            questionsId: id,
            answerOptionsId: Array.isArray(current[id].val) ? current[id].val.join(',') : current[id].val,
            answerContent: ''
          })
        } else if (current[id].type === 'input' && current[id].val && !current[id].optionsLength) {
          filled.push({
            questionsId: id,
            answerOptionsId: '',
            answerContent: current[id].val
          })
        } else if ((current[id].type === 'input' || current[id].type === 'inputs') && current[id].val.length) {
          let arr = []
          for(let i = 0; i < current[id].optionsLength; i++) {
            arr[i] = current[id].val[i] || ''
          }
          filled.push({
            questionsId: id,
            answerOptionsId: '',
            answerContent: arr
          })
        } else if (current[id].flag) {
          filled.push({
            questionsId: id,
            answerOptionsId: '',
            answerContent: current[id].val
          })
        }
        // 未作答
        if ((this.detail.isAllAnswer === '1' || current[id].must === '1') && !current[id].flag && current[id].type !== 'remark' && current[id].type !== 'partition') {
          unfilled.push({
            index: current[id].index,
            location: current[id].location
          })
        }
        if ((this.detail.isAllAnswer === '1' || current[id].must === '1') && current[id].type === 'radio' && current[id].flag && current[id].val && current[id].options[current[id].val].openExtendQuestion === '1' && !current[id].extendAnswer) {
          unfilled.push({
            extend: true,
            index: current[id].index,
            location: current[id].location
          })
        } else if (current[id].type === 'radio' && current[id].flag && current[id].val && current[id].options[current[id].val].openExtendQuestion === '1' && current[id].extendAnswer) {
          extendFilled.push({
            optionsId: current[id].val,
            answerContent: current[id].extendAnswer
          })
        } else if (current[id].type === 'check' && current[id].flag && current[id].val) {
          let custom = current[id].val.find(e => current[id].options[e].openCustomAnswer === '1')
          if (custom && current[id].customAnswer) {
            customFilled.push({
              optionsId: custom,
              answerContent: current[id].customAnswer
            })
          } else if ((this.detail.isAllAnswer === '1' || current[id].must === '1') && custom) {
            unfilled.push({
              extend: true,
              index: current[id].index,
              location: current[id].location
            })
          }
        }
      }
      if (unfilled.length) {
        return {
          filled,
          unfilled,
          extendFilled,
          customFilled
        }
      }
      return {
        filled,
        extendFilled,
        customFilled
      }
    },
    // 跳转未答
    showVali(list) {
      let listAll = deepClone(this.listAll)
      let ob = null
      list.map(e => {
        if (!ob) {
          ob = e
        }
        listAll[e.index].extend = e.extend
        listAll[e.index].fillVali = true
      })
      this.listAll = listAll
      this.handleMove(ob.location)
    },
    // 自动保存答案
    save(fn, fail, flag) {
      let list = this.getJson(this.answer), answerJson = '', extendAnswerJson= '', customAnswerJson = ''
      if (!list.unfilled) {
        answerJson = stringify(list.filled)
        extendAnswerJson = stringify(list.extendFilled)
        customAnswerJson = stringify(list.customFilled)
      } else if (flag && list.unfilled.length) {
        this.showVali(list.unfilled)
        if (fail) fail()
        return false
      } else if (list.filled.length) {
        answerJson = stringify(list.filled)
        extendAnswerJson = stringify(list.extendFilled)
        customAnswerJson = stringify(list.customFilled)
      }
      if (answerJson) {
          if (fn) fn()
      } else {
        if (fn) fn()
      }
    },
    // 保存
    submit() {
      this.saveLoading = true
      this.save(e => {
        const pageLoading = this.$toast.loading('问卷正在提交')
          this.saveLoading = false
          pageLoading.clear()
          this.submitSucc('提交成功')
      }, res => {
        this.saveLoading = false
      }, true)
    },
    // 到时间自动保存
    submitAuto() {
      this.save(e => {
          if (this.timer) {
            clearInterval(this.timer)
          }
          this.submitSucc('问卷已超时，系统已自动交卷')
      })
    },
    submitSucc(text) {
      this.$dialog.alert({
        title: '提示',
        message: text,
        confirmButtonColor: 'var(--color)',
        beforeClose: (action, done) => {
          done()
          this.toResult()
        }
      })
    },
    toResult() {
      this.$uniRedirectTo({
        name: 'questionnaire-result-id',
        params: {
          id: this.detail.recordId
        }, query: {
          surveyId: this.id
        }
      })
    },
    openLink(url) {
      this.actionURL = url
      this.actionShow = true
    },

  },
}
</script>
<style lang="scss" scoped>
.page-containter {
  .nav-bar-btn{
    width: 60px;
    height: 28px;
	font-size: 14px;
  }
  .page-content{
    position: relative;
    z-index: 2;
    .page-bg{
      //position: fixed;
      //z-index: -1;
      width: 100%;
      height: auto;
      background: linear-gradient(318deg, var(--colorl) 0%, var(--color) 100%);
    }
    &.isWap{
      .common-wrap{
        width: 100%;
        &.content-wrap{
          padding: 20px;
        }
      }
    }
  }
  .progress-wrap{
    width: 100%;
  }
  .app-progress{
    position: absolute;
    background: #ebedf0;
    z-index: 100;
    width: 100%;
    height: 4px;
    left: 0;
    .van-progress__portion{
      position: absolute;
      left: 0;
      height: 100%;
      background: 'var(--color)';
      transition: all 0.3s;
    }
  }
  .page-title{
    padding: 40px 0 20px;
    line-height: 30px;
    color: #fff;
    text-align: center;
  }
  .page-subtitle{
    padding: 15px 0 30px;
    line-height: 24px;
    color: #fff;
    text-align: center;
  }
  .common-wrap{
    width: 100%;
    margin: 0 auto;
    &.content-wrap{
      position: relative;
      padding: 65px 120px 60px;
      background: #FFFFFF;
      .btn-wrap{
        width: 100%;
        padding: 20px 0;
        text-align: center;
        button {
          width: 120px;
          & + button {
            margin-left: 20px;
          }
        }
      }
    }
  }
}
</style>
